package link.jfire.socket.socketserver.storage;

import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import link.jfire.baseutil.reflect.ReflectUtil;
import link.jfire.socket.socketserver.bus.ServerChannelInfo;
import sun.misc.Unsafe;

/**
 * 用来表示响应数据的数据包
 * 
 * @author Administrator
 * 
 */
@SuppressWarnings("restriction")
public class WritePacket
{
    private final long          cursor;
    private ServerChannelInfo   serverChannelInfo;
    private volatile ByteBuffer writeBuffer;
    private volatile boolean    flowDone = false;
    private volatile int        writed   = 0;
    private static Unsafe       unsafe   = ReflectUtil.getUnsafe();
    private static long         offset   = ReflectUtil.getFieldOffset("writed", WritePacket.class);
    
    public WritePacket(ServerChannelInfo serverChannelInfo, long cursor)
    {
        this.serverChannelInfo = serverChannelInfo;
        this.cursor = cursor;
    }
    
    public void flowDone(ByteBuffer writeBuffer)
    {
        this.writeBuffer = writeBuffer;
        flowDone = true;
    }
    
    public boolean tryWrite()
    {
        if (serverChannelInfo.isTopWritePacket(this) == false || flowDone == false || writed == 1)
        {
            return false;
        }
        if (unsafe.compareAndSwapInt(this, offset, 0, 1) == false)
        {
            return false;
        }
        serverChannelInfo.getSocketChannel().write(writeBuffer, 10l, TimeUnit.SECONDS, this, serverChannelInfo.getMessageWriteCompleteHandler());
        return true;
    }
    
    public ByteBuffer getBuffer()
    {
        return writeBuffer;
    }
    
    public ServerChannelInfo getServerChannelInfo()
    {
        return serverChannelInfo;
    }
    
    public long cursor()
    {
        return cursor;
    }
}
